package com.iqiyi.pps.epg.core.rpc.qipu.Composite;

import com.google.protobuf.Message;
import com.iqiyi.pps.epg.core.rpc.qipu.QipuRequest;
import knowledge.pub.Common;
import knowledge.pub.Knowledge;
import knowledge.pub.Properties;
import knowledge.pub.WriteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by karkarrotxu on 2014/12/29.
 */
@Service
public class NodeCommonImpl {
    private static final Logger logger = LoggerFactory.getLogger(NodeCommonImpl.class);

    @Autowired
    private QipuRequest qipuRequest;

    public int setObjectDeletedToQipu(Long entityId, boolean del) {
        logger.info("[NodeCommonImpl][setObjectDeletedToQipu][start][entityId={}][del={}]", entityId, del);
        return setDeleteByQipuId(entityId, del);
    }

    public int setDeleteByQipuId(long entityId, boolean del) {
        int rest = (int) (entityId % 100);
        Message.Builder builder = null;
        if (rest == 22) {
            builder = newLiveChannelBuilder(entityId).setDeleted(del);
        } else if (rest == 23) {
            builder = newLiveEpisodeBuilder(entityId).setDeleted(del);
        } else {
            logger.info("setDeleteByQipuId no such rest {}", entityId);
            return -1;
        }
        return writeEntity(builder.build());
    }

    private int callMaxOnce = 150;

    public List<Long> registerQipuId(int type, int total_count) {
        logger.info("[NodeCommonImpl][registerQipuId][start][type={}][total_count={}]", type, total_count);
        int restTotal = total_count <= 0 ? 1 : total_count;
        List<Long> list = new ArrayList<Long>();
        List<Long> temp = null;
        logger.info("registerQipuId start  total_count :" + restTotal);
        while (true) {
            if (restTotal == 0) {
                break;
            }
            int callLength = restTotal > callMaxOnce ? callMaxOnce : restTotal;
            restTotal -= callLength;
            temp = registerResult(Common.EntityIdType.valueOf(type), callLength);
            if (temp == null) {
                restTotal += callLength;
                logger.info("registerQipuId fail at : restTotal:" + restTotal + ";callLength:" + callLength);
            } else {
                list.addAll(temp);
            }
        }
        logger.info("registerQipuId end  restTotal :" + restTotal);
        return list;
    }

    private List<Long> registerResult(Common.EntityIdType type, int totalCount) {
        List<Long> ids = null;
        try {
            ids = qipuRequest.getIdService().getNewIds(type, totalCount);
            logger.info("[NodeCommonImpl][registerQipuId][finish][result={}]", ids);
        } catch (Exception e) {
            logger.error("[NodeCommonImpl][registerQipuId][error]", e);
        }
        return ids;
    }

    public Message getEntityByqipuId(Long qipuId) {
        logger.info("[QipuManager][getEntityByqipuId][start][qipuId={}]", qipuId);
        if (qipuId == null) {
            return null;
        }
        Message message = null;
        try {
            message = qipuRequest.getReadService().getEntity(qipuId);
        } catch (Exception e) {
            logger.error("[getEntityByqipuId][qipuId=" + qipuId + "]", e);
        }
        return message;
    }

    public int writeEntity(Message message) {
        long _startTime = System.currentTimeMillis();
        try {
            WriteService.WriteResponse response = qipuRequest.getWriteService().addEntity(message);
            logger.info("[writeEntity][back][number={}][message={}]", response.getRpcStatusInfo().getRpcStatus().getNumber(), response.getRpcStatusInfo().getRpcStatus().getValueDescriptor());
            return response.getRpcStatusInfo().getRpcStatus().getNumber();
        } catch (Exception e) {
            logger.error("[writeEntity][error][e={}]", e);
            return -1;
        } finally {
            long _endTime = System.currentTimeMillis();
            logger.info("[writeEntity][time={}]", (_endTime - _startTime));
        }
    }

    public int setEntity(Message message,Message deleteMessage) {
        long _startTime = System.currentTimeMillis();
        try {
            WriteService.WriteResponse response = qipuRequest.getWriteService().setEntity(message,deleteMessage);
            logger.info("[setEntity][back][number={}][message={}]", response.getRpcStatusInfo().getRpcStatus().getNumber(), response.getRpcStatusInfo().getRpcStatus().getValueDescriptor());
            return response.getRpcStatusInfo().getRpcStatus().getNumber();
        } catch (Exception e) {
            logger.error("[setEntity][error][e={}]", e);
            return -1;
        } finally {
            long _endTime = System.currentTimeMillis();
            logger.info("[setEntity][time={}]", (_endTime - _startTime));
        }
    }

    public int setEntity(Message message,Message deleteMessage,boolean shouldNotify, boolean batchMode) {
        long _startTime = System.currentTimeMillis();
        try {
            WriteService.WriteResponse response = qipuRequest.getWriteService().setEntity(message,deleteMessage, shouldNotify, batchMode);
            logger.info("[setEntity][back][number={}][message={}]", response.getRpcStatusInfo().getRpcStatus().getNumber(), response.getRpcStatusInfo().getRpcStatus().getValueDescriptor());
            return response.getRpcStatusInfo().getRpcStatus().getNumber();
        } catch (Exception e) {
            logger.error("[setEntity][error][e={}]", e);
            return -1;
        } finally {
            long _endTime = System.currentTimeMillis();
            logger.info("[setEntity][time={}]", (_endTime - _startTime));
        }
    }

    public int deleteEntity(Message message){
        long _startTime = System.currentTimeMillis();
        try {
            WriteService.WriteResponse response = qipuRequest.getWriteService().deleteEntity(message);
            logger.info("[deleteEntity][back][number={}][message={}]", response.getRpcStatusInfo().getRpcStatus().getNumber(), response.getRpcStatusInfo().getRpcStatus().getValueDescriptor());
            return response.getRpcStatusInfo().getRpcStatus().getNumber();
        } catch (Exception e) {
            logger.error("[deleteEntity][error][e={}]", e);
            return -1;
        } finally {
            long _endTime = System.currentTimeMillis();
            logger.info("[deleteEntity][time={}]", (_endTime - _startTime));
        }
    }

    public Knowledge.LiveChannel getLiveChannel(long qipuId) {
        logger.info("[getLiveChannel][qipuId={}]", qipuId);
        if (qipuId < 1) {
            return null;
        }
        Knowledge.LiveChannel liveChannel = (Knowledge.LiveChannel) getEntityByqipuId(qipuId);
        return liveChannel;
    }

    public Knowledge.LiveEpisode getLiveEpisode(long qipuId) {
        logger.info("[getLiveChannel][qipuId={}]", qipuId);
        if (qipuId < 1) {
            return null;
        }
        Knowledge.LiveEpisode liveEpisode = (Knowledge.LiveEpisode) getEntityByqipuId(qipuId);
        return liveEpisode;
    }

    public Knowledge.LiveChannel.Builder newLiveChannelBuilder(long qipuId){
        return Knowledge.LiveChannel.newBuilder().setId(qipuId);
    }

    public Knowledge.LiveEpisode.Builder newLiveEpisodeBuilder(long qipuId){
        return Knowledge.LiveEpisode.newBuilder().setId(qipuId);
    }

    public Properties.Qitan.Builder getQitan(long entityId, boolean show) {
        Properties.Qitan.Builder qitan = Properties.Qitan.newBuilder();
        qitan.setEntityId(entityId); // 奇谈ID
        qitan.setShouldDisplay(show);
        return qitan;
    }
}
